class Shop::OrdersController < ShopController
  def index
    @orders = current_shoper.shop.orders
    if params[:between].presence
      if params[:between] == 'today'
        @orders = @orders.today
      elsif params[:between] == 'by_week'
        @orders = @orders.by_week
      elsif params[:between] == 'by_month'
        @orders = @orders.by_month
      end
    end
    if params[:state].presence
      @orders = @orders.where(state: params[:state])
    end
    if params[:search_key].presence
      @orders = @orders.where("trade_no LIKE ?", "%#{params[:search_key]}%")
    end
    @orders = @orders.order("created_at DESC").page(params[:page]).per(params[:per])
  end

  def show
    @order = Order.find params[:id]
  end

  def edit
    @order = Order.find params[:id]
  end
  
  def update
    @order = Order.find params[:id]
    is_checkouted = @order.checkouted?
    if @order.update order_params
      if @order.pending?
        @order.send_notify("商家已修改订单金额,请查看.", 'Native', 'order_details', '{ "id": ' + @order.id.to_s + ' }')
      elsif is_checkouted && @order.sent?
        @order.order_items.update_all(state: :sent)
        @order.send_notify("订单已发货.", 'Native', 'order_details', '{ "id": ' + @order.id.to_s + ' }')
      end
      redirect_to edit_shop_order_path(@order), notice: "修改成功."
    else
      redirect_to edit_shop_order_path(@order), notice: "修改失败."
    end
  end

  private

  def order_params
    params.require(:order).permit(:state, :logistics_company_id, :logistics_trade_no, :total_fee)
  end
  
end
